package com.utilities.IO.fileWriters;

import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

import com.utilities.dataStructures.NameValuePair;
import com.utilities.parsers.ecocyc.pathwayColParser.ParseEvents;
import com.utilities.parsers.ecocyc.pathwayColParser.ParseListener;
import com.utilities.parsers.ecocyc.pathwayColParser.ParsePathwayColFileParser;

public class GeneToPathwayMapper extends ParseListener{

	HashMap<String, ArrayList<NameValuePair>> genes = null;
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception  
	{
		GeneToPathwayMapper geneToPathwayMapper = new GeneToPathwayMapper();
		ParsePathwayColFileParser classFileParser = new ParsePathwayColFileParser();
		classFileParser.addListener(geneToPathwayMapper);
		classFileParser.parse(new File("C:/Users/bansalp/Desktop/pathways.col"));
		geneToPathwayMapper.writeFile("C:/Users/bansalp/Desktop/resulsssst.txt");
	}
	
	public void run(String pathwaysFile) throws Exception
	{
		ParsePathwayColFileParser classFileParser = new ParsePathwayColFileParser();
		classFileParser.addListener(this);
		classFileParser.parse(new File(pathwaysFile));
	}

	private void writeFile(String string) throws Exception  
	{
		PrintWriter pw = new PrintWriter(string);
		Set<String> keys = genes.keySet();
		for (String key : keys)
		{
			pw.println(key);
			ArrayList<NameValuePair> lst = genes.get(key);
			for (NameValuePair pairs : lst)
			{
				pw.println("\t" + pairs.getName() + "\t" + pairs.getValue());
			}
		}
		pw.flush();
		pw.close();
		
	}

	@Override
	public void handleEvent(ParseEvents event) {
		switch((ParseEvents.EventTypes)event.getEventType())
		{
		case comment:
			break;
		case docStarted:
			genes = new HashMap<String, ArrayList<NameValuePair>>();
			break;
		case docEnded:
			break;
		case headerLine:
			break;
		case row:
			String readLine = (String)event.getSource();
			String[] params = readLine.split("\t");
			NameValuePair nameValuePair = new NameValuePair(params[0], params[1]);
			for (int i = 2; i <= 119; i++)
			{
				if (params[i].equals("")) break;
				ArrayList<NameValuePair> lst = null;
				if (genes.containsKey(params[i]))lst= genes.get(params[i]);
				else lst = new ArrayList<NameValuePair>();
				lst.add(nameValuePair);
				genes.put(params[i], lst);
			}
			break;
		}
	}
	
	public ArrayList<NameValuePair> getForGene(String geneName)
	{
		if (!genes.containsKey(geneName)) return null;
		else return new ArrayList<NameValuePair>(genes.get(geneName));
	}
}
